<?php
namespace app\lib\exception;
use think\exception\Handle;
use think\Exception;
use think\Request;
use think\Log;

class ExceptionHandler extends Handle{
		private $code;
		private $msg;
		private $errorCode;
    //需要返回客户端当前请求的URL路径

    //必须调用基类\exception
	public function render(\Exception $e)
	{
      //判断异常是否是来自BaseException
		if ($e instanceof BaseException) {
			//如果是自定义异常
			$this->code = $e->code;
			$this->msg = $e->msg;
			$this->errorCode = $e->errorCode;
            $this->recordErrorLog( $e);
		} else {
		    //if是一个开关 意思是如果开启了debug则调用正常的render方法返回调试信息给客户端
			if (config('app_debug')) {
				return parent::render($e);
				//如果没开debug则返回我们自定义的数据给客户端
			} else {
				$this->code = 500;
				$this->msg = '服务器内部错误';
				$this->errorCode = 999;
				$this->recordErrorLog($e);
			}
		}
		$request = Request::instance();

		$result = [
			'msg' => $this->msg,
			'error_code' => $this->errorCode,
			'request_url' => $request->url() //获取当前请求URL
			];
		return json($result,$this->code);
	}
	//必须调用基类\exception
	private function recordErrorLog(\Exception $e)
	{
	    //初始化日志信息 因为日志信息在config中被我手动关闭了
		Log::init([
			'type' => 'File',
			'path' => LOG_PATH,
			'level' => ['error']
			]);
		Log::record($e->getMessage(),'error');
	}
}